package com.android.fragmentdemo.util
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.android.fragmentdemo.ILoadDataCallback
import com.android.fragmentdemo.R
import com.android.fragmentdemo.rxjava.BaseObserver
import com.android.fragmentdemo.rxjava.SchedulerTransformer
import io.reactivex.rxjava3.core.Observable
import java.net.HttpURLConnection
import java.net.URL

object UrlConvertBitmapUtil {

    private const val IMG_URL = "http://b247.photo.store.qq.com/psb?/V11ZojBI312o2K/63aY8a4M5quhi.78*krOo7k3Gu3cknuclBJHS3g1fpc!/b/dDXWPZMlBgAA"

    fun convertUrlToBitmap(context: Context, callback: ILoadDataCallback<MutableList<Bitmap>>?) {
        val urlList = mutableListOf<String>()
        for (i in 0.until(20)) {
            urlList.add(IMG_URL)
        }

        val resultList = mutableListOf<Bitmap>()
        Observable
            .fromIterable(urlList)
            .flatMap {
                var bmp: Bitmap? = null
                try {
                    val connection = URL(it).openConnection() as HttpURLConnection
                    connection.doInput = true
                    connection.connect()
                    val input = connection.inputStream
                    bmp = BitmapFactory.decodeStream(input)
                    input.close()
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
                /*val observable = Observable.create<Bitmap> { emitter ->
                    if (bmp != null) {
                        emitter.onNext(bmp)
                    } else {
                        emitter.onError(RuntimeException())
                    }
                }*/
                //observable.subscribe
                if (bmp == null) {
                    val placeHolder = BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)
                    Observable.just(placeHolder)
                } else {
                    Observable.just(bmp)
                }
            }.compose(SchedulerTransformer())
            .subscribe(object : BaseObserver<Bitmap>() {
                override fun onComplete() {
                    super.onComplete()
                    callback?.loadDataSuccess(resultList)
                }
                override fun onNext(data: Bitmap) {
                    super.onNext(data)
                    resultList.add(data)
                }
            })
    }
}